﻿<%@ WebHandler Language="C#" Class="ContainerStepPlanRateDashBoard" %>

using System;
using System.IO;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using System.Collections.Generic;
using System.Data;
using System.Text;
using ReportBusiness;
using System.Net;

/**
 * Description: 订单排产率看板(生产部)
 * Copyright (c): 通力凯顿（北京）系统集成有限公司
 * Author: zhunan
 * Date: 2022.6.16
 */

public class ContainerStepPlanRateDashBoard : IHttpHandler
{
    uMESReportOracleDAL dal = new uMESReportOracleDAL();
    public bool IsReusable { get { return false; } }
    public void ProcessRequest(HttpContext context)
    {
        string requestjson = "";
        using (StreamReader reader = new StreamReader(context.Request.InputStream)) { requestjson = reader.ReadToEnd(); }
        JObject jObject = JsonConvert.DeserializeObject(requestjson) as JObject;
        if (jObject["type"] != null)
        {
            try
            {
                Result r = new Result();
                context.Response.ContentType = "text/json";
                string type = jObject["type"].ToString();
                switch (type)
                {
                    case "getData":
                        r = getData(jObject);
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "getDetail":
                        r = getDetail(jObject);//明细
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    case "getExportExcel":
                        getExportExcel(jObject);//导出
                        break;
                    default:
                        break;
                }
            }
            catch (Exception e)
            {
                Result r = new Result();
                r.data = null;
                r.meta = new Result.Meta(500, e.Message);
                r.total = 0;
                context.Response.ContentType = "text/json";
                context.Response.Write(JsonConvert.SerializeObject(r));
            }
        }
    }

    Result getData(JObject jObject)
    {
        JArray selectDate = JArray.Parse(jObject["selectdate"].ToString());
        string sql = @"
SELECT t.factoryname,COUNT(1) total,SUM(DECODE(t.status,'未排产',0,'已排产',1)) planqty,
       COUNT(1)-SUM(DECODE(t.status,'未排产',0,'已排产',1)) notplanqty,
       ROUND(SUM(DECODE(t.status,'未排产',0,'已排产',1)) / COUNT(1),4) * 100 planrate
FROM
(
  SELECT f.factoryname,mfg.mfgordername,cci.containername,ws.workflowstepname,
         CASE WHEN csp.containerstepplanid IS NULL THEN '未排产' ELSE '已排产' END status 
  FROM containercurrentinfo cci
  LEFT JOIN mfgorder mfg ON cci.mfgorderid = mfg.mfgorderid
  LEFT JOIN mes_factory_mapping f ON f.factoryid = cci.originalfactoryid
  LEFT JOIN Workflowstep ws ON ws.workflowid = NVL(cci.bsworkflowid,cci.workflowid)
  LEFT JOIN containerstepplan csp ON csp.containerid = cci.containerid AND csp.workflowstepid = ws.workflowstepid
  LEFT JOIN specbase sb ON sb.specbaseid = ws.specbaseid
  LEFT JOIN spec s ON s.specid = NVL(sb.revofrcdid,ws.specid)
  LEFT JOIN containerstepnoship csn ON csn.containerid = cci.containerid AND csn.workflowstepid = ws.workflowstepid AND csn.noship = 2 AND csn.isuse = 0
  LEFT JOIN containercommidetail cmm ON cmm.containerid = cci.containerid AND cmm.workflowstepid = ws.workflowstepid AND cmm.isuse = 0
  WHERE cci.containerstatus = 1 AND NVL(cci.workflowroute,'0') = '0' AND ws.workflowstepname <> '完工入库'
        AND NVL(s.controlcode,'LY01') <> 'LY05' AND csn.containerstepnoshipid IS NULL AND cmm.containercommidetailid IS NULL
        AND f.factorycode IN ('601','609','607','600','608')
        AND mfg.plannedcompletiondate >= to_date('{0}','yyyy-MM-dd') AND mfg.plannedcompletiondate <= to_date('{1}','yyyy-MM-dd')
) t
GROUP BY t.factoryname";
        sql = string.Format(sql, selectDate[0].ToString(), selectDate[1].ToString());
        DataTable dt = dal.GetDataTable(sql);
        foreach (DataColumn col in dt.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        Result r = new Result();
        r.data = dt;
        r.total = Convert.ToInt32(dt.Rows.Count);
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    string getDetailSql(JObject jObject)
    {
        JArray selectDate = JArray.Parse(jObject["selectdate"].ToString());
        string sql = @"
SELECT f.factoryname,mfg.mfgordername,cci.containername,ws.sequence,ws.workflowstepname,
       CASE WHEN csp.containerstepplanid IS NULL THEN '未排产' ELSE '已排产' END status,
       csp.stepplancreatedate,e.fullname,nvl(csp.plannedfinishdate,csp.plannedstartdate) plannedfinishdate 
FROM containercurrentinfo cci
LEFT JOIN mfgorder mfg ON cci.mfgorderid = mfg.mfgorderid
LEFT JOIN Factory f ON f.factoryid = cci.originalfactoryid
LEFT JOIN Workflowstep ws ON ws.workflowid = NVL(cci.bsworkflowid,cci.workflowid)
LEFT JOIN containerstepplan csp ON csp.containerid = cci.containerid AND csp.workflowstepid = ws.workflowstepid
LEFT JOIN employee e ON e.employeeid = csp.stepplancreateemployeeid
LEFT JOIN specbase sb ON sb.specbaseid = ws.specbaseid
LEFT JOIN spec s ON s.specid = NVL(sb.revofrcdid,ws.specid)
LEFT JOIN containerstepnoship csn ON csn.containerid = cci.containerid AND csn.workflowstepid = ws.workflowstepid AND csn.noship = 2 AND csn.isuse = 0
LEFT JOIN containercommidetail cmm ON cmm.containerid = cci.containerid AND cmm.workflowstepid = ws.workflowstepid AND cmm.isuse = 0
WHERE cci.containerstatus = 1 AND NVL(cci.workflowroute,'0') = '0' AND ws.workflowstepname <> '完工入库'
      AND NVL(s.controlcode,'LY01') <> 'LY05' AND csn.containerstepnoshipid IS NULL AND cmm.containercommidetailid IS NULL
      AND mfg.plannedcompletiondate >= to_date('{0}','yyyy-MM-dd') AND mfg.plannedcompletiondate <= to_date('{1}','yyyy-MM-dd') AND f.factoryname = '{2}'";

        if (jObject["seriesName"].ToString() == "已排产")
        {
            sql += " AND NVL(csp.containerstepplanid,'0') <> '0' ";
        }

        if (jObject["seriesName"].ToString() == "未排产")
        {
            sql += " AND NVL(csp.containerstepplanid,'0') = '0' ";
        }

        sql += @"
ORDER BY f.factoryname,mfg.mfgordername,cci.containername,ws.sequence";
        sql = string.Format(sql, selectDate[0].ToString(), selectDate[1].ToString(), jObject["factoryname"].ToString());
        return sql;
    }

    Result getDetail(JObject jObject)
    {
        string sql = getDetailSql(jObject);
        uMESPagingDataDTO dto = dal.GetPagingDataIns(sql, (int)jObject["currentPage"], (int)jObject["pageSize"]);
        DataTable dt = dto.DBTable;
        foreach (DataColumn col in dt.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        Result r = new Result();
        r.data = dt;
        r.total = Convert.ToInt32(dto.RowCount);
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }

    void getExportExcel(JObject jObject)
    {
        string sql = getDetailSql(jObject);
        DataTable dt = dal.GetDataTable(sql);
        foreach (DataColumn col in dt.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        dt.Columns["factoryname"].Caption = "主制分厂";
        dt.Columns["mfgordername"].Caption = "订单号";
        dt.Columns["containername"].Caption = "流水卡号";
        dt.Columns["sequence"].Caption = "工序号";
        dt.Columns["workflowstepname"].Caption = "工序名称";
        dt.Columns["stepplancreatedate"].Caption = "排产日期";
        dt.Columns["fullname"].Caption = "排产人";
        dt.Columns["plannedfinishdate"].Caption = "排产要求完成日期";
        dt.Columns["status"].Caption = "状态";
        ExportHelper.ExportExcel(dt, jObject["title"].ToString());
    }
}